<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Download, CopyDocument, Link } from "@element-plus/icons-vue";
import ImagePreview from "@/components/ImagePreview.vue";
import {
  getGoodPageApi,
  getGoodCategoriesApi,
  updateGoodEnableApi,
  type GoodInfo,
  type GoodsCategoryRecord,
  type GoodUpdateEnableReq,
} from "@/api/good";
import BannerForm from "./components/BannerForm.vue";
import {
  BannerInfo,
  disaleBannerApi,
  enbaleBannerApi,
  getBannerPageApi,
} from "@/api/banner";

// 查询参数类型
interface SearchType {
  id: string;
  keyword: string;
  enable: boolean | null;
}

// 查询参数
const searchParams = ref<SearchType>({
  id: "",
  keyword: "",
  enable: null,
});

// 物品分类选项
const categoryOptions = ref<GoodsCategoryRecord[]>([]);

// 图片预览相关
const previewVisible = ref(false);
const previewImageUrl = ref("");
const previewTitle = ref("");

// 动效预览相关
const animationPreviewVisible = ref(false);
const animationPreviewUrl = ref("");
const animationPreviewTitle = ref("");

// 物品表单相关
const goodFormVisible = ref(false);
const currentGoodData = ref<BannerInfo | null>(null);
const isEditMode = ref(false);

// 数据列表和分页
const dataList = ref<BannerInfo[]>([]);
const loading = ref(false);
const totals = ref(0);
const pageInfo = ref({
  page: 1,
  pageSize: 10,
});

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    const params = {
      ...searchParams.value,
      pageNo: pageInfo.value.page,
      pageSize: pageInfo.value.pageSize,
    };

    // 过滤空值参数
    const requestParams = Object.fromEntries(
      Object.entries(params).filter(([_, value]) => {
        return value !== "" && value !== null && value !== undefined;
      })
    );

    const response = await getBannerPageApi(requestParams);
    const { data } = response;
    dataList.value = data.list;
    totals.value = data.total;
  } catch (error) {
    console.error("加载数据失败:", error);
    ElMessage.error("加载数据失败");
  } finally {
    loading.value = false;
  }
};

// 加载物品分类
const loadCategories = async () => {
  try {
    const response = await getGoodCategoriesApi();
    categoryOptions.value = response.data;
  } catch (error) {
    console.error("加载物品分类失败:", error);
  }
};

// 查询方法
const handleSearch = () => {
  pageInfo.value.page = 1;
  loadData();
};

// 重置方法
const handleReset = () => {
  searchParams.value = {
    id: "",
    keyword: "",
    enable: null,
  };
  pageInfo.value.page = 1;
  loadData();
};

// 新增物品
const handleAdd = () => {
  isEditMode.value = false;
  currentGoodData.value = null;
  goodFormVisible.value = true;
};

// 编辑物品
const handleEdit = (row: BannerInfo) => {
  isEditMode.value = true;
  currentGoodData.value = { ...row };
  goodFormVisible.value = true;
};

// 切换上架状态
const handleToggleStatus = async (row: BannerInfo) => {
  const newEnable = !row.enable;
  const actionText = newEnable ? "上架" : "下架";
  const itemName = row.title;

  try {
    await ElMessageBox.confirm(
      `确定要${actionText}物品"${itemName}"吗？`,
      `${actionText}确认`,
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true,
      }
    );

    if (newEnable) {
      await enbaleBannerApi(row.id);
    } else {
      await disaleBannerApi(row.id);
    }

    // 更新本地数据
    row.enable = newEnable;

    ElMessage.success(`${actionText}成功`);
  } catch (error) {
    if (error === "cancel") {
      // 用户取消操作，不做任何处理
      return;
    }
    console.error("切换状态失败:", error);
    ElMessage.error(`${actionText}失败`);
  }
};

// 分页方法
const handleSizeChange = (size: number) => {
  pageInfo.value.pageSize = size;
  pageInfo.value.page = 1;
  loadData();
};

const handleCurrentChange = (page: number) => {
  pageInfo.value.page = page;
  loadData();
};

// 图片预览
const handlePreviewImage = (url: string, title: string) => {
  previewImageUrl.value = url;
  previewTitle.value = title;
  previewVisible.value = true;
};

// 获取文件扩展名
const getFileExtension = (url: string) => {
  const extension = url.split(".").pop()?.toUpperCase();
  return extension || "未知格式";
};

// 下载动效文件
const downloadAnimation = () => {
  const link = document.createElement("a");
  link.href = animationPreviewUrl.value;
  link.download = `animation.${getFileExtension(
    animationPreviewUrl.value
  ).toLowerCase()}`;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  ElMessage.success("开始下载动效文件");
};

// 复制动效链接
const copyAnimationUrl = async () => {
  try {
    await navigator.clipboard.writeText(animationPreviewUrl.value);
    ElMessage.success("链接已复制到剪贴板");
  } catch (error) {
    ElMessage.error("复制失败");
  }
};

// 新窗口打开动效
const openAnimationInNewTab = () => {
  window.open(animationPreviewUrl.value, "_blank");
};

// 获取分类名称
const getTypeName = (category: string) => {
  const typeOptions = [
    { key: "0", desc: "h5 url" },
    { key: "1", desc: "app内页面" },
  ];

  const found = typeOptions.find((item) => item.key == category);
  return found ? found.desc : category;
};
const getSubTypeName = (category: string) => {
  const typeOptions = [
    { key: "0", desc: "端内Webview 打开" },
    { key: "1", desc: "外部浏览器打开" },
  ];

  const found = typeOptions.find((item) => item.key == category);
  return found ? found.desc : category;
};

// 获取分类标签样式
const getTagType = (category: string) => {
  const typeOptions = [
    { key: "0", desc: "h5 url" },
    { key: "1", desc: "app内页面" },
  ];

  const found = typeOptions.find((item) => item.key == category);
  if (!found) return "info";

  // 根据分类的code值来分配不同的标签样式
  const tagTypes = ["", "primary", "success", "warning", "danger", "info"];
  const typeIndex = Number(found.key) % tagTypes.length;
  return tagTypes[typeIndex] || "info";
};

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return "-";
  const date = new Date(dateString);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
};

// 处理表单提交
const handleFormSubmit = () => {
  loadData(); // 重新加载数据
};

// 组件挂载时加载数据
onMounted(() => {
  loadCategories();
  loadData();
});
</script>

<template>
  <div class="good-list">
    <!-- 查询区域 -->
    <el-card class="mb">
      <el-form :model="searchParams" inline>
        <el-form-item label="活动名称">
          <el-input
            v-model="searchParams.keyword"
            placeholder="请输入活动名称"

            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="上架状态">
          <el-select
            v-model="searchParams.enable"
            placeholder="请选择上架状态"
            clearable
            style="width: 200px"
          >
            <el-option label="已上架" :value="true" />
            <el-option label="未上架" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button
            type="success"
            @click="handleAdd"
            style="margin-left: 10px"
          >
            <el-icon><Plus /></el-icon>
            上传Banner
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card>
      <el-table
        :data="dataList"
        v-loading="loading"
        :fit="true"
        style="width: 100%"
      >
        <el-table-column
          prop="id"
          label="序号"
          type="index"
          min-width="80"
          index-method="(index) => index + 1"
          show-overflow-tooltip
        />

        <el-table-column prop="title" label="活动名称" min-width="120" />
        <el-table-column label="Banner图" min-width="360" show-overflow-tooltip>
          <template #default="{ row }">
            <div>
              <img
                v-if="row.imageUrl"
                :src="row.imageUrl"
                width="180"
                height="60"
                class="good-avatar"
                @click="handlePreviewImage(row.imageUrl, row.title)"
                style="
                  cursor: pointer;
                  object-fit: cover;
                  border-radius: 4px;
                  margin-right: 10px;
                "
              />
              <img
                v-if="row.arImageUrl"
                :src="row.arImageUrl"
                width="180"
                height="60"
                class="good-avatar"
                @click="handlePreviewImage(row.arImageUrl, row.title)"
                style="cursor: pointer; object-fit: cover; border-radius: 4px"
              />
            </div>
          </template>
        </el-table-column>

        <el-table-column
          prop="type"
          label="打开方式"
          min-width="120"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <el-tag :type="getTagType(row.type)">
              {{ getTypeName(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="subType"
          label="跳转方式"
          min-width="140"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <el-tag :type="getTagType(row.subType)">
              {{ getSubTypeName(row.subType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="url"
          label="链接"
          min-width="200"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <el-link v-if="row.type == 0" :href="row.url" target="_blank">{{
              row.url
            }}</el-link>

            <div v-if="row.type == 1 && row.params">
              <div>安卓链接：{{ row.params.android }}</div>
              <div>Ios链接：{{ row.params.ios }}</div>
              <div>H5链接：{{ row.params.h5 }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column
          prop="createTime"
          label="创建时间"
          min-width="180"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <span>{{ formatDate(row.createTime) }}</span>
          </template>
        </el-table-column>

        <el-table-column
          prop="endTime"
          label="结束时间"
          min-width="180"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <span>{{ formatDate(row.endTime) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="状态" min-width="100" show-overflow-tooltip>
          <template #default="{ row }">
            <el-tag :type="row.enable ? 'success' : 'danger'">
              {{ row.enable ? "已上架" : "未上架" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button
              :type="row.enable ? 'warning' : 'success'"
              size="small"
              @click="handleToggleStatus(row)"
            >
              {{ row.enable ? "下架" : "上架" }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pageInfo.page"
          v-model:page-size="pageInfo.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totals"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 图片预览弹框 -->
    <ImagePreview
      v-model="previewVisible"
      :image-url="previewImageUrl"
      :title="previewTitle"
    />

    <!-- 物品表单弹框 -->
    <BannerForm
      v-model="goodFormVisible"
      :good-data="currentGoodData"
      :is-edit="isEditMode"
      @submit="handleFormSubmit"
    />
  </div>
</template>

<style scoped lang="less">
.good-list {
  padding: 20px;

  .mb {
    margin-bottom: 20px;
  }

  .good-avatar {
    border: 1px solid #e4e7ed;
    transition: transform 0.3s;

    &:hover {
      transform: scale(1.1);
    }
  }

  .animation-container {
    display: flex;
    align-items: center;

    .animation-preview {
      display: flex;
      align-items: center;
      gap: 5px;
      color: #409eff;
      font-size: 12px;

      &:hover {
        color: #66b1ff;
      }
    }

    .no-animation {
      display: flex;
      align-items: center;
      gap: 5px;
      color: #909399;
      font-size: 12px;
    }
  }

  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #e4e7ed;
  }
}

.animation-preview-dialog {
  .animation-preview-content {
    .animation-info {
      margin-bottom: 20px;

      p {
        margin: 10px 0;
        line-height: 1.6;
      }
    }

    .animation-actions {
      display: flex;
      gap: 10px;
      justify-content: center;
    }
  }
}
</style>
